package com.project.class4_11.model.prototype;

import java.io.*;

public class Man implements Cloneable, Serializable {
    private String name;
    private int age;
    private Car car;

    public Man(String name, int age, String type) {
        this.name = name;
        this.age = age;
        this.car = new Car(type);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    /**
     * 浅克隆，克隆对象的引用类型属性和原对象引用类型的属性，引用的是同一个对象
     * @return 克隆对象。
     */
    @Override
    public Man clone()  {
        try {
            return (Man)super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 深度克隆
     * @return 克隆对象
     */
    public Man deepClone(){
        ByteArrayOutputStream byteOut = null;
        ObjectOutputStream objOut = null;
        ByteArrayInputStream byteIn = null;
        ObjectInputStream objIn = null;

        try {
            byteOut = new ByteArrayOutputStream();
            objOut = new ObjectOutputStream(byteOut);
            //将当前对象写入字节数组
            objOut.writeObject(this);

            //创建字节读取流。数据来自之前写入的字节数组
            byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            objIn = new ObjectInputStream(byteIn);

            //将对象读取流中的数据，还原对象
            return (Man)objIn.readObject();
        }catch (Exception e){
            e.printStackTrace();
        }finally{
            try {
                objIn.close();
                byteIn.close();
                objOut.close();
                byteOut.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    public String toString() {
        return "Man{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", car=" + car +
                '}';
    }
}
